package com.bwie.redkids;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.bwie.redkids.adapter.NewProductAdapter;
import com.bwie.redkids.bean.NewProductBean;
import com.bwie.redkids.bean.NewProductBean.MyProductListBean;
import com.bwie.redkids.utils.GsonUtils;
import com.bwie.redkids.utils.PathUtils;
import com.google.gson.Gson;

public class NewProductActivity extends Activity implements OnClickListener {

	private ListView product_list;
	private int SUCESS = 0;
	private ArrayList<MyProductListBean> arrayList = new ArrayList<NewProductBean.MyProductListBean>();

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == SUCESS) {
				NewProductBean newProductBean = (NewProductBean) msg.obj;
				arrayList.addAll(newProductBean.getProductlist());
				product_list.setAdapter(new NewProductAdapter(
						NewProductActivity.this, arrayList));
			}
		};
	};
	private Button product_back;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_new_product);
		product_list = (ListView) findViewById(R.id.product_list);
		product_back = (Button) findViewById(R.id.product_back);
		product_back.setOnClickListener(this);
		getFlashInformation();
		product_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(NewProductActivity.this,
						DetailsActivity.class);
				intent.putExtra("id", arrayList.get(arg2).getId());
				startActivity(intent);
			}
		});
	}

	private void getFlashInformation() {
		new Thread() {
			public void run() {
				try {
					String data = GsonUtils.getData(PathUtils.PATH
							+ PathUtils.NEWPRODUCT);
					Gson gson = new Gson();
					NewProductBean fromJson = gson.fromJson(data,
							NewProductBean.class);

					handler.obtainMessage(SUCESS, fromJson).sendToTarget();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.product_back:
			NewProductActivity.this.finish();
			break;

		default:
			break;
		}
	}
}
